import RouteRecognizer, { Result } from "route-recognizer";
import { Observe, Stack } from "../util";
import * as normalize from "./normalize";
export default class RouterInternal {
    private routeRecognizer: RouteRecognizer = new RouteRecognizer();
    protected currentRoute: RevealableRoute;
    private currentWindow: Window;
    private fromPath: string = "";
    private toPath: string = "";
    private observe: Observe = new Observe();
    constructor(public root: HTMLIFrameElement, router: RouteConfig[]) {
        // TODO 修改RouteRecognizer代码，实现添加数组功能
        normalize.normalizeRoutes(router).forEach(item => {
            this.routeRecognizer.add([item]);
        });
        window.addEventListener("hashchange", e => {
            this.route(location.hash.slice(1));
        })
    }
    //TODO 策略模式，做多种模式渲染
    protected render() {
        const that = this;
        console.log("render");
        that.root.setAttribute("src", `./${that.currentRoute.name}.html`);
        let _window = that.root.contentWindow;
        that.root.onload = function () {
            document.title = that.currentRoute.title;
            that.observe.fire("globalRouteAfter", _window, that.currentRoute, that.fromPath, that.toPath);
            Object.freeze(that.currentRoute);
        }

    }
    protected route(path: string): Result {
        const that = this;
        path = normalize.normalizePath(path);
        let res = that.routeRecognizer.recognize(path);
        if (!res) {
            this.observe.fire('pageNotFound');
            return undefined;
        }
        that.fromPath = window.location.hash.slice(1);
        that.toPath = path;
        window.location.hash = that.toPath;
        that.observe.fire("globalRouteBefore", window
            , that.currentRoute, that.fromPath, path);
        that.currentRoute = normalize.normalizeRoute(res[0]);
        this.render();
        return res[0]
    }
    protected notFound(cb: Function) {
        this.observe.register('pageNotFound', cb);
    }
    protected addRouteItem(item: RouteConfig) {
        this.routeRecognizer.add(normalize.normalizeRoutes([item]))
    }
    //TODO 没有实现单个路由的钩子函数
    protected addBeforeLeave(cb: Function, scope: string = "global") {
        this.observe.register(scope + "RouteLeave", cb);
    }
    protected addAfterEnter(cb: Function, scope: string = "global") {
        this.observe.register(scope + "RouteAfter", cb);
    }
}